package pl.dsp.dsp1.ui;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import pl.dsp.dsp1.processing.ComplexValue;
import pl.dsp.dsp1.processing.Signal;
import pl.dsp.dsp1.processing.SignalValue;
import pl.dsp.dsp1.processing.SimpleValue;

public class SignalJSON {
	private Signal signal;
	private JSONObject json;

	@SuppressWarnings("unchecked")
	public SignalJSON(Signal signal) {
		this.signal = new Signal(signal);

		json = new JSONObject();
		json.put("samplingPeriod", new Double(signal.getSamplingPeriod()));
		json.put("t1", new Double(signal.getT1()));
		json.put("dimensions", new Integer(signal.getDimensions()));
		json.put("length", new Integer(signal.getXAxis().size()));

		JSONArray values = new JSONArray();
		for (SignalValue value : signal) {
			JSONArray valueArray = new JSONArray();
			for (int dimension = 0; dimension < signal.getDimensions(); dimension++) {
				valueArray.add(new Double(value.getValues().get(dimension)));
			}
			values.add(valueArray);
		}

		json.put("values", values);
	}

	public SignalJSON(JSONObject json) {
		this.json = new JSONObject(json);

		Double t1 = (Double) json.get("t1");
		Double samplingPeriod = (Double) json.get("samplingPeriod");
		signal = new Signal(t1, samplingPeriod);

		Long dimensions = (Long) json.get("dimensions");

		JSONArray values = (JSONArray) json.get("values");
		for (Object valueObject : values) {
			JSONArray valueArray = (JSONArray) valueObject;
			if (dimensions == 1) {
				signal.add(new SimpleValue((Double) valueArray.get(0)));
			} else if (dimensions == 2) {
				signal.add(new ComplexValue((Double) valueArray.get(0),
						(Double) valueArray.get(1)));
			}
		}
	}

	public Signal getSignal() {
		return signal;
	}

	public JSONObject getJSON() {
		return json;
	}
}
